import React, { useState, useEffect, memo } from "react";
import {
  Layout,
  Popover,
  Menu,
  Breadcrumb,
  Button,
  Tag,
  Dropdown,
  Popconfirm,
  Message,
} from "@arco-design/web-react";
import {
  IconHome,
  IconCalendar,
  IconMenuFold,
  IconMenuUnfold,
  IconMoonFill,
  IconSunFill,
  IconApps,
  IconUserGroup,
  IconMessage,
  IconLiveBroadcast,
  IconVideoCamera,
  IconBook,
  IconStorage,
  IconUser,
  IconSettings,
  IconSelectAll,
  IconClose,
  IconQq,
  IconWechat,
  IconFaceSmileFill,
  IconDown,
  IconCheckCircle,
  IconVoice,
} from "@arco-design/web-react/icon";
import "@arco-design/web-react/dist/css/arco.css";
import { HomeWrapper } from "./style";
import logo from "../../../public/favicon.ico";
import { Outlet, useNavigate } from "react-router-dom";
import { Logout } from "../../service/modules/login";
import { findMatchItem } from "../../utils/findMatchItem";
import { useAppDispatch, useAppSelector } from "../../store";
import { fetchGetUserInfoAction } from "../../store/modules/login";

const { Item: MenuItem, SubMenu } = Menu;
const { Sider, Header, Footer, Content } = Layout;

const HomePage = () => {
  const [collapsed, setCollapsed] = useState(false); //折叠slider
  const [darkMode, setDarkMode] = useState(false);

  const dispatch = useAppDispatch();
  const [breadcrumbItems, setBreadcrumbItems] = useState<
    { label: string; key: string }[]
  >([{ label: "首页", key: "/home/index" }]);
  const [secondBreadItems, setSecondBreadItems] = useState<
    {
      label: string;
      key: string;
    }[]
  >([{ label: "首页", key: "/home/index" }]);

  const { userInfo } = useAppSelector((state) => state.login);
  // console.log(userInfo);

  const navigate = useNavigate();
  // const [navigateKey, setNavigateKey] = useState("");
  const handleCollapsed = () => {
    setCollapsed(!collapsed);
  };
  // console.log(location.replace("http://localhost:5174/#/", ));
  const toggleDarkMode = () => {
    if (darkMode) {
      document.body.removeAttribute("arco-theme");
    } else {
      document.body.setAttribute("arco-theme", "dark");
    }
    setDarkMode(!darkMode);
  };
  useEffect(() => {
    if (!userInfo) {
      navigate("/login");
    }
  }, [userInfo]);
  useEffect(() => {
    dispatch(fetchGetUserInfoAction());
  }, [dispatch]);
  // 检查系统主题偏好
  useEffect(() => {
    const darkThemeMq = window.matchMedia("(prefers-color-scheme: dark)");
    const handleSystemThemeChange = (e: any) => {
      if (e.matches) {
        document.body.setAttribute("arco-theme", "dark");
        setDarkMode(true);
      } else {
        document.body.removeAttribute("arco-theme");
        setDarkMode(false);
      }
    };
    // 初始检查
    if (darkThemeMq.matches) {
      document.body.setAttribute("arco-theme", "dark");
      setDarkMode(true);
    }
    // 监听系统主题变化
    darkThemeMq.addEventListener("change", handleSystemThemeChange);
    return () => {
      darkThemeMq.removeEventListener("change", handleSystemThemeChange);
    };
  }, []);
  //点击左侧菜单栏同步first和second面包屑
  const handleMenuClick = (key: string) => {
    navigate(key);
    updateBreadItem(key);
    updateSecondBreadItems(key);
  };
  // 获取 Hash 模式下的真实路径
  const getActualPath = () => {
    if (location.hash) {
      const hashPath = location.hash.replace("#", "");
      return hashPath.startsWith("/") ? hashPath : `/${hashPath}`;
    }
    return location.pathname;
  };
  // //最靠上的面包屑逻辑
  // const updateBreadItem = (path: string) => {
  //   const menuItem = findMatchItem(menuItems, path);
  //   // console.log(menuItem);
  //   // console.log(path);
  //   if (path === "/home/index") {
  //     if (breadcrumbItems.length > 1) {
  //       breadcrumbItems.pop();
  //     }
  //     return breadcrumbItems;
  //   } else {
  //     // console.log(breadcrumbItems);
  //     if (breadcrumbItems.length > 1) {
  //       breadcrumbItems.pop();
  //     } else {
  //       const isAppear = breadcrumbItems.some((item) => {
  //         return item.key === getActualPath();
  //       });
  //       if (isAppear) {
  //         return breadcrumbItems;
  //       } else {
  //         breadcrumbItems.push(menuItem);
  //       }
  //     }
  //   }
  // };
  // //secondBread相关操作
  // const updateSecondBreadItems = (path: string) => {
  //   const menuItem = findMatchItem(menuItems, path);
  //   if (path === "/home/index") {
  //     return secondBreadItems;
  //   } else {
  //     const isAppear = secondBreadItems.some((item) => {
  //       return item.key === getActualPath();
  //     });
  //     if (isAppear) {
  //       return secondBreadItems;
  //     } else {
  //       secondBreadItems.push(menuItem);
  //       // setSecondBreadItems((prev) => {
  //       // return [...prev, menuItem];
  //       // });
  //     }
  //   }
  // };
  const updateBreadItem = (path: string) => {
    if (path === "/home/index") {
      setBreadcrumbItems([{ label: "首页", key: "/home/index" }]);
    } else {
      const menuItem = findMatchItem(menuItems, path);
      if (menuItem) {
        setBreadcrumbItems([{ label: "首页", key: "/home/index" }, menuItem]);
      }
    }
  };
  const updateSecondBreadItems = (path: string) => {
    const menuItem = findMatchItem(menuItems, path);
    if (!menuItem) return;

    setSecondBreadItems((prev) => {
      // 如果路径是首页，重置
      // if (path.includes( "/home/workplace/taskExamination/")) {
      //  return [...prev,]
      // }

      // 如果已经存在，不重复添加
      if (prev.some((item) => item.key === path)) {
        return prev;
      }

      // 否则添加新项
      return [...prev, menuItem];
    });
  };

  //初始化First面包屑
  useEffect(() => {
    const currentPath = getActualPath();
    if (currentPath !== "/home/index") {
      const menuItem = findMatchItem(menuItems, currentPath);
      if (menuItem) {
        setBreadcrumbItems([{ label: "首页", key: "/home/index" }, menuItem]);
      }
    }
  }, []);
  // console.log(breadcrumbItems);

  //初始化second面包屑
  useEffect(() => {
    const currentPath = getActualPath();
    if (currentPath !== "/home/index") {
      const menuItem = findMatchItem(menuItems, currentPath);
      if (menuItem) {
        setSecondBreadItems([{ label: "首页", key: "/home/index" }, menuItem]);
      }
    }
  }, [getActualPath()]);

  const menuItems = [
    {
      label: "首页",
      key: "/home/index",
      icon: <IconHome />,
      isShow: true,
    },
    {
      label: "工作台",
      key: "/workplace",
      icon: <IconApps />,
      isShow: true,
      children: [
        // {
        //   label: "病人检查和任务",
        //   key: "/home/workplace/taskExamination/:id",
        //   icon: <IconUserGroup />,
        //   isShow: false,
        // },
        {
          label: "病人管理",
          key: "/home/workplace/patient",
          icon: <IconCheckCircle />,
        },
        {
          label: "留言管理",
          key: "/home/workplace/leaveword",
          icon: <IconMessage />,
        },
      ],
    },
    {
      label: "多媒体",
      key: "/media",
      icon: <IconLiveBroadcast />,

      children: [
        {
          label: "文章管理",
          key: "/home/media/article",
          icon: <IconBook />,
        },

        {
          label: "视频管理",
          key: "/home/media/video",
          icon: <IconVideoCamera />,
        },
      ],
    },
    {
      label: "信息管理",
      key: "/inforManage",
      icon: <IconCalendar />,

      children: [
        {
          label: "方案制定",
          key: "/home/inforManage/programme",
          icon: <IconSelectAll />,
        },
        {
          label: "ai对话",
          key: "/home/inforManage/aichart",
          icon: <IconVoice />,
        },
        // {
        //   label: "帖子管理",
        //   key: "/home/inforManage/post",
        // },
        // {
        //   label: "病种管理",
        //   key: "/home/inforManage/illness",
        // },
        // {
        //   label: "任务管理",
        //   key: "/home/inforManage/task",
        // },
        // {
        //   label: "文章评论",
        //   key: "/home/inforManage/articleComment",
        // },
        // {
        //   label: "帖子评论",
        //   key: "/home/inforManage/postComment",
        // },
      ],
    },
    {
      label: "系统管理",
      key: "/system",
      icon: <IconSettings />,
      isShow: true,

      children: [
        {
          label: "用户管理",
          key: "/home/user",
          icon: <IconUser />,
          isShow: true,
        },
      ],
    },
  ];

  //删除second面白屑
  // console.log(secondBreadItems);

  const clearSecondBreadItems = (path: string) => {
    setSecondBreadItems((prev: any) => {
      // console.log(prev);
      const newItems = prev.filter((item: any) => item.key !== path);
      if (getActualPath() === path) {
        const lastItem = newItems[newItems.length - 1];
        if (lastItem) {
          setTimeout(() => {
            navigate(lastItem.key);
          }, 0);
        } else {
          navigate("/home/index");
        }
      }
      // console.log("1");

      return newItems;
    });
  };
  //点击跳转
  const handleSecondBreadClick = (key: string) => {
    // 确保item是简单对象，不包含React元素或上下文
    navigate(key);
  };
  //初始化first和second面包屑
  useEffect(() => {
    updateBreadItem(getActualPath());
    updateSecondBreadItems(getActualPath());
  }, [navigate]);

  const outLoginProps = {
    title: "你确定要等退出登入吗？",
    onOk: () => {
      Logout().then(() => {
        navigate("/login");
      });
      Message.info({
        content: "欢迎下次登入我的网页",
      });
    },
    onCancel: () => {
      Message.info({
        content: "我就知道你舍不得离开~",
      });
    },
    onClick: (e: any) => {
      e.stopPropagation(); // 阻止事件冒泡到下拉菜单
    },
  };

  const dropList = (
    <Menu
      onClick={() => {
        console.log("进入个人中心");
      }}
    >
      <Menu.Item key="userCenter" style={{ userSelect: "none" }}>
        个人中心
      </Menu.Item>
      <Menu.Item
        key="outLogin"
        onClick={(e) => {
          e.stopPropagation();
        }}
        style={{ userSelect: "none" }}
      >
        <Popconfirm
          position="bottom"
          {...outLoginProps}
          icon={<IconFaceSmileFill />}
        >
          退出登录
        </Popconfirm>
      </Menu.Item>
    </Menu>
  );
  return (
    <HomeWrapper>
      <Layout className="layout-collapse-demo">
        <Sider collapsed={collapsed} collapsible trigger={null} breakpoint="xl">
          <div className="logo">
            <img src={logo}></img>
            <p>术后康复智能管理系统</p>
          </div>
          <Menu
            selectedKeys={[getActualPath()]}
            defaultOpenKeys={["/home/index"]}
            defaultSelectedKeys={[getActualPath()]}
            onClickMenuItem={handleMenuClick}
            style={{ width: "100%" }}
          >
            {menuItems.map((item) =>
              item.children ? (
                <SubMenu
                  key={item.key}
                  title={
                    <span>
                      {item.icon}
                      {item.label}
                    </span>
                  }
                >
                  {item.children.map((child) => (
                    <MenuItem key={child.key}>
                      <span>
                        {child.icon}
                        {child.label}
                      </span>
                    </MenuItem>
                  ))}
                </SubMenu>
              ) : (
                <MenuItem key={item.key}>
                  {item.icon}
                  {item.label}
                </MenuItem>
              )
            )}
          </Menu>
        </Sider>
        <Layout>
          <Header
            style={{
              display: "flex",
              position: "relative",
              alignItems: "center",
            }}
          >
            <Button
              className="trigger"
              onClick={handleCollapsed}
              style={{ marginRight: 16 }}
            >
              {collapsed ? (
                <IconMenuFold
                  style={{
                    width: "20px",
                    height: "20px",
                  }}
                />
              ) : (
                <IconMenuUnfold
                  style={{
                    width: "20px",
                    height: "20px",
                  }}
                />
              )}
            </Button>
            <Breadcrumb>
              {breadcrumbItems.map((item) => {
                return (
                  <Breadcrumb.Item key={item.key}>{item.label}</Breadcrumb.Item>
                );
              })}
            </Breadcrumb>
            <div className="right-icons">
              <Popover position="bottom" title="2970768980">
                <Button
                  className="btn"
                  shape="circle"
                  icon={<IconQq />}
                ></Button>
              </Popover>
              <Popover position="bottom" title="whitelittleya">
                <Button
                  className="btn"
                  shape="circle"
                  icon={<IconWechat />}
                ></Button>
              </Popover>
              <Button
                className="btn"
                shape="circle"
                onClick={toggleDarkMode}
                icon={darkMode ? <IconSunFill /> : <IconMoonFill />}
              />
            </div>
            {/* 头像下拉 */}
            <Dropdown droplist={dropList} trigger="click" position="bottom">
              <div className="userimg">
                <img src={`http://119.29.235.74:20242${userInfo.avatar}`}></img>
                <IconDown
                  style={{
                    position: "absolute",
                    right: "-20px",
                    top: "25px",
                    userSelect: "none",
                    cursor: "pointer",
                  }}
                />
              </div>
            </Dropdown>
          </Header>
          <div className="secondBread">
            {secondBreadItems.map((item, index) => {
              if (item.key !== getActualPath()) {
                return (
                  <Tag
                    key={item.key}
                    className="tag"
                    onClick={() => {
                      handleSecondBreadClick(item.key);
                    }}
                  >
                    {item.label}
                    {index > 0 && (
                      <span className="close-icon">
                        <IconClose
                          onClick={(e) => {
                            e.stopPropagation();
                            clearSecondBreadItems(item.key);
                          }}
                        />
                      </span>
                    )}
                  </Tag>
                );
              }
              return (
                <Tag
                  key={item.key}
                  className="tag clickBread"
                  onClick={() => {
                    handleSecondBreadClick(item.key);
                  }}
                >
                  {item.label}
                  {index > 0 && (
                    <span className="close-icon">
                      <IconClose
                        onClick={(e) => {
                          e.stopPropagation();
                          clearSecondBreadItems(item.key);
                        }}
                      />
                    </span>
                  )}
                </Tag>
              );
            })}
          </div>
          <Layout
            style={{ padding: "0 24px", borderTop: "1px solid #c8cfe1ff" }}
          >
            {/* 二级路由 */}
            <Content>
              <div style={{ width: "100%" }}>
                <Outlet />
              </div>
            </Content>
            <Footer style={{ textAlign: "center" }}>
              一个准大二前端小菜鸟写的网页,上面有我qq和微信,可以一起交流前端知识
            </Footer>
          </Layout>
        </Layout>
      </Layout>
    </HomeWrapper>
  );
};

export default memo(HomePage);
